package com.eat.fish_service.filter;

import com.eat.common_utils.JwtUtils;
import com.eat.common_utils.R;
import com.eat.common_utils.ResponseUtil;
import com.eat.fish_service.service.UserService;
import com.eat.servicebase.config.InterceptorConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author CZF
 * @create 2022-09-03 0:15
 *
 * 此方法实现自动登录太麻烦，抛弃！换成HeaderAutoLoginFilter
 *
 * 用于实现自动登录的过滤器
 * 如果"/web/user/login"请求中带有token，则不需要再登录，直接返回用户数据和更新cookie
 *
 */

//@WebFilter(filterName = "autoLoginFilter", urlPatterns = "/web/user/login")
public class AutoLoginFilter implements Filter {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserService userService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        Cookie cookie = JwtUtils.getToken(req); //从req中获取存token的cookie对象
        if(cookie ==null) {  //如果cookie中没有token,则用户还未登录过，通过chain.doFilter(request,response)放行请求到登录接口
            chain.doFilter(request,response);
        }else{
            boolean isValid = JwtUtils.checkTokenByCookie(cookie,redisTemplate); //和redis中存储的token校验，看token是否有效
            if(isValid){
                String username = JwtUtils.getUsername(cookie.getValue()); //从token中获取用户名
                R r = userService.getUserMess(username,req,res); //获取用户信息
                ResponseUtil.out(req,res,r);//使用ResponseUtil工具类返回响应
            }else { //token无效
                chain.doFilter(request,response);
            }
        }
    }
}
